<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="框架,spring," />





  <link rel="alternate" href="/atom.xml" title="聪聪的独立博客" type="application/atom+xml" />






<meta name="description" content="前言 有一段时间没有更新记录了，正好今天是周五。公司给的一个小项目里面有自己封装的框架，闲暇时光看一看… 无意之中看到了封装分页的的底层方法中使用了这样的注解。  1234@Transactional(       readOnly = true,       propagation = Propagation.NOT_SUPPORTED   ) 那我就顺便学习，总结下@Transactional">
<meta name="keywords" content="框架,spring">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring篇——简单理解@Transactional注解中propagation的使用">
<meta property="og:url" content="https://chencong-plan.github.io/2018/01/12/transacation-propagation/index.html">
<meta property="og:site_name" content="聪聪的独立博客">
<meta property="og:description" content="前言 有一段时间没有更新记录了，正好今天是周五。公司给的一个小项目里面有自己封装的框架，闲暇时光看一看… 无意之中看到了封装分页的的底层方法中使用了这样的注解。  1234@Transactional(       readOnly = true,       propagation = Propagation.NOT_SUPPORTED   ) 那我就顺便学习，总结下@Transactional">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-18T01:36:32.306Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring篇——简单理解@Transactional注解中propagation的使用">
<meta name="twitter:description" content="前言 有一段时间没有更新记录了，正好今天是周五。公司给的一个小项目里面有自己封装的框架，闲暇时光看一看… 无意之中看到了封装分页的的底层方法中使用了这样的注解。  1234@Transactional(       readOnly = true,       propagation = Propagation.NOT_SUPPORTED   ) 那我就顺便学习，总结下@Transactional">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://chencong-plan.github.io/2018/01/12/transacation-propagation/"/>





  <title>Spring篇——简单理解@Transactional注解中propagation的使用 | 聪聪的独立博客</title>
  
<style>
  .forkme{
 display: none;
 }
  @media (min-width: 768px) {
 .forkme{
 display: inline;
 }
  }
  </style>

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?042a886f72a663c61ed2f77aeae32cb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <div class="forkme">
     <a target="_blank" href="https://github.com/chencong-plan"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://camo.githubusercontent.com/567c3a48d796e2fc06ea80409cc9dd82bf714434/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f6c6566745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_left_darkblue_121621.png"></a>
    </div>
 
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">聪聪的独立博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">挥舞这本子，做个ccoder</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-messagesboard">
          <a href="/messagesBoard/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            留言板
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chencong-plan.github.io/2018/01/12/transacation-propagation/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="聪聪不匆匆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/author.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="聪聪的独立博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring篇——简单理解@Transactional注解中propagation的使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-12T14:23:45+08:00">
                2018-01-12
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-01-18T09:36:32+08:00">
                2018-01-18
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/spring/" itemprop="url" rel="index">
                    <span itemprop="name">spring</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2018/01/12/transacation-propagation/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2018/01/12/transacation-propagation/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2018/01/12/transacation-propagation/" class="leancloud_visitors" data-flag-title="Spring篇——简单理解@Transactional注解中propagation的使用">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,596
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><blockquote>
<p>有一段时间没有更新记录了，正好今天是周五。公司给的一个小项目里面有自己封装的框架，闲暇时光看一看…</p>
<p>无意之中看到了封装分页的的底层方法中使用了这样的注解。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span>(</span><br><span class="line">       readOnly = <span class="keyword">true</span>,</span><br><span class="line">       propagation = Propagation.NOT_SUPPORTED</span><br><span class="line">   )</span><br></pre></td></tr></table></figure>
<p>那我就顺便学习，总结下<code>@Transactional</code>注解当中<code>propagation</code>属性的一些用法和特征吧，充充电。</p>
<h2 id="看看源码"><a href="#看看源码" class="headerlink" title="看看源码"></a>看看源码</h2><h3 id="Transactional有哪些属性呢"><a href="#Transactional有哪些属性呢" class="headerlink" title="@Transactional有哪些属性呢"></a>@Transactional有哪些属性呢</h3><p>在<code>Spring</code>的事务管理当中，我们一直都是使用<code>@Transactional</code>注解来对事务进行设定的。简而言之，在类或者方法上使用<code>@Transactional</code>注解，并且传输属性获得相应的Transaction特性。<code>Spring</code>当中对于<code>@Transactional</code>注解的属性从源码查看如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.METHOD, ElementType.TYPE&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Inherited</span></span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Transactional &#123;</span><br><span class="line">    <span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> ""</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">Propagation <span class="title">propagation</span><span class="params">()</span> <span class="keyword">default</span> Propagation.REQUIRED</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">Isolation <span class="title">isolation</span><span class="params">()</span> <span class="keyword">default</span> Isolation.DEFAULT</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">timeout</span><span class="params">()</span> <span class="keyword">default</span> -1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">readOnly</span><span class="params">()</span> <span class="keyword">default</span> <span class="keyword">false</span></span>;</span><br><span class="line"></span><br><span class="line">    Class&lt;? extends Throwable&gt;[] rollbackFor() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    String[] rollbackForClassName() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    Class&lt;? extends Throwable&gt;[] noRollbackFor() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    String[] noRollbackForClassName() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从源码当中可以看出<code>@Transactional</code>有<code>propagation</code> <code>isolation</code> <code>timeout</code> <code>readOnly</code> <code>rollbackForClassName</code> <code>noRollbackForClassName</code> 等属性。 </p>
<p><code>isolation</code>是设置事务隔离，<code>timeout</code>事务超时，<code>readOnly</code> 定义该事务的方法只读，默认为false，<code>rollbackForClassName</code> 定义回滚条件，比如发生<code>RuntimeException</code>时候发生回滚，<code>noRollbackForClassName</code> 不回滚，有些异常时正常情况，不进行回滚。通过这些属性可以定义出满足复杂应用事务的要求。</p>
<h3 id="具体看看propagation属性"><a href="#具体看看propagation属性" class="headerlink" title="具体看看propagation属性"></a>具体看看propagation属性</h3><p>在Service层类上使用<code>@Transactional</code>注解，声明这个类所有方法需要事务管理，每一个业务方法开始时候都会打开一个事务，每一个方法所需要的事物管理级别特性的不同，就需要我们使用 <code>@Transactional</code> 当中这些属性来操作了。</p>
<p><code>Spring</code>默认情况下是对<code>RuntimeException</code>运行期异常进行事务回滚，并且只对于运行时异常当中的<code>unchecked</code>异常回滚，对于<code>checked</code>异常就不回滚，对于<code>checked</code> <code>unchecked</code>异常分类不在这里记录，之后再进行记录。</p>
<p>上面说到默认对运行时异常当中的<code>unchecked</code>异常进行回滚，那么问题来了，我们想要实现对<code>checked</code>异常进行回滚怎么办呢？当然有方法可以处理的，就需要使用到上面说到的属性。</p>
<ul>
<li>让<code>checked</code>异常回滚</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span>(rollbackFor = Exception.class)</span><br></pre></td></tr></table></figure>
<ul>
<li>让<code>unchecked</code>异常不回滚</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span>(noRollbackFor = RuntimeException.class)</span><br></pre></td></tr></table></figure>
<ul>
<li>查询操作不需要事务</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span>(propagation = Propagation.NOT_SUPPORTED)</span><br></pre></td></tr></table></figure>
<p>或者</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span>(propagation = Propagation.NOT_SUPPORTED,readOnly = <span class="keyword">true</span>)</span><br></pre></td></tr></table></figure>
<p>将这个方法做成了一个只读事务，提高效率。</p>
<p>说了这么多还不知道<code>Propagation</code>是个什么东西呢，这是一个枚举类型，里面定义了该属性的各种意义：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> Propagation &#123;</span><br><span class="line">    REQUIRED(<span class="number">0</span>),</span><br><span class="line">    SUPPORTS(<span class="number">1</span>),</span><br><span class="line">    MANDATORY(<span class="number">2</span>),</span><br><span class="line">    REQUIRES_NEW(<span class="number">3</span>),</span><br><span class="line">    NOT_SUPPORTED(<span class="number">4</span>),</span><br><span class="line">    NEVER(<span class="number">5</span>),</span><br><span class="line">    NESTED(<span class="number">6</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> value;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">Propagation</span><span class="params">(<span class="keyword">int</span> value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">value</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Propagation的各枚举含义"><a href="#Propagation的各枚举含义" class="headerlink" title="Propagation的各枚举含义"></a>Propagation的各枚举含义</h3><p>上面已经将<code>Propagation</code>当中各个枚举列举出来了，它们都是什么含义呢？</p>
<ul>
<li><strong>REQUIRED</strong>(必须)</li>
</ul>
<p>业务方法需要在一个容器当中运行。如果该方法运行时候已经处在一个事务中，那么加入该事务，否则自己新建事务。<br>这个是<code>默认值</code></p>
<ul>
<li><strong>SUPPORTS</strong>(支持)</li>
</ul>
<p>如果业务方法在某个事务范围内被调用，则成为该事务的一部分。如果该业务方法在事务范围之外被调用，则在没有事务环境下运行。（有则改之无则加勉，有则用之无则不用）</p>
<ul>
<li><strong>MANDATORY</strong>(强制性)</li>
</ul>
<p>业务方法只能在一个已经存在的事物当中执行，不能够自己发起事务。如果该业务方法在没有事务环境下运行则会抛出异常(<code>IllegalTransactionStateException</code>)。</p>
<ul>
<li><strong>REQUIRES_NEW</strong>(需要新的)</li>
</ul>
<p>不管事务是否存在，该业务方法都会自己新建一个新的事务。如果业务方法已经运行在一个事务当中，则原来的事务被挂起，新事务被创建。</p>
<ul>
<li><strong>NOT_SUPPORTED</strong></li>
</ul>
<p>业务方法不需要事务。如果该业务方法运行没有关联到事务，则不会为其开启事务；如果该业务方法在一个事务当中被调用，该事务被挂起，调用结束后，原先事务恢复执行。</p>
<ul>
<li><strong>NEVER</strong></li>
</ul>
<p>业务方法绝对不能再事务范围内执行。如果在就抛出异常(<code>IllegalTransactionStateException</code>)。只有不关联任务事务才正常执行。</p>
<ul>
<li><strong>NESTED</strong></li>
</ul>
<p>业务方法执行时存在一个活动的事务，那么该方法运行在一个嵌套的事务当中，作为子事务。如果没有活动事务则按照<code>REQUIRED</code> 属性来执行。该属性使用一个单独的事务，拥有很多个可以回滚的保存点，内部事务的回滚不会对外部事务造成影响。</p>
<h2 id="举个栗子吧"><a href="#举个栗子吧" class="headerlink" title="举个栗子吧"></a>举个栗子吧</h2><p>上面说了这么多了，下面举个栗子，说一下吧。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="meta">@Transactional</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestTransactional</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IExampleDao exampleDao;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Transactional</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">internalMethod</span><span class="params">()</span></span>&#123;</span><br><span class="line">        exampleDao.doSomething();</span><br><span class="line">        externalMethod();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Transactional</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">externalMethod</span><span class="params">()</span></span>&#123;</span><br><span class="line">        exampleDao.doSomething();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>先上一段伪代码。在<code>Service</code>层定义两个方法，分别为<code>internalMethod</code> 和 <code>externalMetod</code>。然后里面都调用<code>exampleDao</code>当中的<code>doSomething()</code>方法。下面就来根据上面列举出来的<code>Propagation</code>的属性来讨论事务。</p>
<table>
<thead>
<tr>
<th>Propagation属性</th>
<th>externalMethod</th>
<th>internalMethod</th>
</tr>
</thead>
<tbody>
<tr>
<td>Propagation.REQUIRED(<code>默认</code>)</td>
<td>此时无事务，新开始一个事务并在其中运行</td>
<td>在<code>externalMethod</code>方法的事务中运行</td>
</tr>
<tr>
<td>Propagation.SUPPORTS</td>
<td><code>externalMethod</code>无事务，不在事务中运行</td>
<td>加入<code>externalMethod</code>事务中运行</td>
</tr>
<tr>
<td>Propagation.MANDATORY</td>
<td>抛出异常</td>
<td>在<code>externalMethod</code>事务中运行</td>
</tr>
<tr>
<td>Propagation.REQUIRES_NEW</td>
<td>新开启事务并在其中运行</td>
<td>挂起<code>externalMethod</code>中事务，直至<code>internalMethod</code>中新开事务运行完毕</td>
</tr>
<tr>
<td>Propagation.NOT_SUPPORTED</td>
<td><code>externalMethod</code>无事务，不在事务中运行</td>
<td>挂起<code>externalMethod</code>中事务，直至<code>internalMethod</code>方法执行完毕(注意这里不是事务，是方法)</td>
</tr>
<tr>
<td>Propagation.NEVER</td>
<td><code>externalMethod</code>无事务，不在事务中运行</td>
<td>抛出异常(不能在事务中运行)</td>
</tr>
</tbody>
</table>
<p>下回就统计统计上面说到的<code>unchecked</code> <code>checked</code> 异常吧。</p>
<h2 id="联系"><a href="#联系" class="headerlink" title="联系"></a>联系</h2><p><a href="https://ccoder.cc/" target="_blank" rel="noopener">聪聪</a>的独立博客 ，一个喜欢技术，喜欢钻研的95后。如果你看到这篇文章，千里之外，我在等你联系。</p>
<ul>
<li><a href="https://ccoder.cc/" target="_blank" rel="noopener">Blog@ccoder’s blog</a></li>
<li><a href="http://blog.csdn.net/chencong3139" target="_blank" rel="noopener">CSDN@ccoder</a></li>
<li><a href="https://github.com/chencong-plan" target="_blank" rel="noopener">Github@ccoder</a></li>
<li><a href="mailto:admin@ccoder.top" target="_blank" rel="noopener">Email@ccoder</a> <em>or</em> <a href="mailto:chencong3139@gmail.com" target="_blank" rel="noopener">Gmail@ccoder</a></li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat_pay.png" alt="聪聪不匆匆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/ali_pay.png" alt="聪聪不匆匆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    聪聪不匆匆
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://chencong-plan.github.io/2018/01/12/transacation-propagation/" title="Spring篇——简单理解@Transactional注解中propagation的使用">https://chencong-plan.github.io/2018/01/12/transacation-propagation/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/框架/" rel="tag"><i class="fa fa-tag"></i> 框架</a>
          
            <a href="/tags/spring/" rel="tag"><i class="fa fa-tag"></i> spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/03/insertion-sort/" rel="next" title="算法篇——插入排序InsertionSort">
                <i class="fa fa-chevron-left"></i> 算法篇——插入排序InsertionSort
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/13/package-response/" rel="prev" title="简单总结下服务器响应类的封装">
                简单总结下服务器响应类的封装 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/author.png"
                alt="聪聪不匆匆" />
            
              <p class="site-author-name" itemprop="name">聪聪不匆匆</p>
              <p class="site-description motion-element" itemprop="description">hello，every body!~</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/chencong-plan" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:1042738887@qq.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-globe"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://blog.csdn.net/chencong3139" target="_blank" title="CSDN">
                    
                      <i class="fa fa-fw fa-globe"></i>CSDN</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/chencong3139" title="CSDN" target="_blank">CSDN</a>
                  </li>
                
              </ul>
            </div>
          

          <div id="music163player">
   <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=496620009&auto=0&height=66"></iframe>
</div>

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text"><a href="#&#x524D;&#x8A00;" class="headerlink" title="&#x524D;&#x8A00;"></a>&#x524D;&#x8A00;</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#看看源码"><span class="nav-number">2.</span> <span class="nav-text"><a href="#&#x770B;&#x770B;&#x6E90;&#x7801;" class="headerlink" title="&#x770B;&#x770B;&#x6E90;&#x7801;"></a>&#x770B;&#x770B;&#x6E90;&#x7801;</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Transactional有哪些属性呢"><span class="nav-number">2.1.</span> <span class="nav-text"><a href="#Transactional&#x6709;&#x54EA;&#x4E9B;&#x5C5E;&#x6027;&#x5462;" class="headerlink" title="@Transactional&#x6709;&#x54EA;&#x4E9B;&#x5C5E;&#x6027;&#x5462;"></a>@Transactional&#x6709;&#x54EA;&#x4E9B;&#x5C5E;&#x6027;&#x5462;</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#具体看看propagation属性"><span class="nav-number">2.2.</span> <span class="nav-text"><a href="#&#x5177;&#x4F53;&#x770B;&#x770B;propagation&#x5C5E;&#x6027;" class="headerlink" title="&#x5177;&#x4F53;&#x770B;&#x770B;propagation&#x5C5E;&#x6027;"></a>&#x5177;&#x4F53;&#x770B;&#x770B;propagation&#x5C5E;&#x6027;</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Propagation的各枚举含义"><span class="nav-number">2.3.</span> <span class="nav-text"><a href="#Propagation&#x7684;&#x5404;&#x679A;&#x4E3E;&#x542B;&#x4E49;" class="headerlink" title="Propagation&#x7684;&#x5404;&#x679A;&#x4E3E;&#x542B;&#x4E49;"></a>Propagation&#x7684;&#x5404;&#x679A;&#x4E3E;&#x542B;&#x4E49;</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#举个栗子吧"><span class="nav-number">3.</span> <span class="nav-text"><a href="#&#x4E3E;&#x4E2A;&#x6817;&#x5B50;&#x5427;" class="headerlink" title="&#x4E3E;&#x4E2A;&#x6817;&#x5B50;&#x5427;"></a>&#x4E3E;&#x4E2A;&#x6817;&#x5B50;&#x5427;</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#联系"><span class="nav-number">4.</span> <span class="nav-text"><a href="#&#x8054;&#x7CFB;" class="headerlink" title="&#x8054;&#x7CFB;"></a>&#x8054;&#x7CFB;</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">聪聪不匆匆</span>

<!--以下3行为一条竖线和Coding Page-->
  <div class="powered-by">  
  </div>
  <span>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></span>
</div>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">17.2k</span>
  
</div>









        







        
      </div>
    </footer>

    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytb0COPK';
      var conf = 'f4ec61439cc0436460d4314634c8eb78';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  









  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("ydueKuP9DBwlcJdmt9zWF1VV-gzGzoHsz", "QfeANi9TLulHoKgHq6V0XJ0U");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  


  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
</body>
</html>
